import axios from 'axios'
import { baseUrl, requestApi } from './env'
import { Toast } from 'vant'

// 发起外部api网络请求
export function OutRequest(config) {
  // 创建axios的实例
  const instance2 = axios.create({
    baseURL: baseUrl,
    timeout: 10000,
  })
  // 请求头部信息为post请求设置
  instance2.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    // 请求拦截
    instance2.interceptors.request.use(
      config => {
        Toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true
        })
        config.headers.Authorization = localStorage.getItem('token') || ''
        return config
      },
      error => {
        return Promise.error(error)
      }
    )
    // 响应拦截
    instance2.interceptors.response.use(response => {
      console.log(response)
      Toast.clear()
      return response.data
    }, err => {
      Toast.fail('请求超时')
      return err
    })
  // 发送真正的网络请求
  return instance2(config)
}

// 发起网络请求
export function request(config) {
  // 创建axios的实例
  const instance = axios.create({
    baseURL: requestApi,
    timeout: 5000,
  })
  // 请求头部信息为post请求设置
  instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

  // 请求拦截
  instance.interceptors.request.use(
    config => {
      Toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true
      })
      config.headers.Authorization = localStorage.getItem('token') || ''
      return config
    },
    error => {
      setTimeout(() => {
        Toast.fail('请求超时')
        Toast.clear()
      }, 1000)
      return Promise.error(error)
    }
  )
  // 响应拦截
  instance.interceptors.response.use(response => {
    console.log(response)
    Toast.clear()
    return response.data
  }, err => {
    return err
  })

  // 发送真正的网络请求
  return instance(config)
}
